import os

import xlsxwriter as xlsxwriter
from django.conf import settings
from django.http import HttpResponseRedirect
from django.views.decorators.csrf import csrf_protect

from app.models import ProductSpec


@csrf_protect
def product_analysis(request):
    query_set = ProductSpec.objects.all()
    the_file_name = "product.xlsx"
    write_excel(os.path.join(settings.MEDIA_ROOT, the_file_name), query_set)
    return HttpResponseRedirect(os.path.join(settings.MEDIA_URL, the_file_name))


def write_excel(file_name, product_list):
    with xlsxwriter.Workbook(file_name) as workbook:  # 建立文件
        # 所有商品汇总
        write_products(workbook, product_list)


def write_products(workbook, specs: [ProductSpec]):
    bold = workbook.add_format({'bold': 1})
    products_ws_titles = [u'类型', u'商品名称', u'规格名称', u'单价（元）', u'单位', u'描述', u'押金', u'押金描述', u'优惠价（元）']
    spec_on_shelf = workbook.add_worksheet(u'上架商品')  # 建立sheet，可以work.add_worksheet('employee')来指定sheet名
    spec_off_shelf = workbook.add_worksheet(u'未上架商品')  # 建立sheet，可以work.add_worksheet('employee')来指定sheet名
    for i, title in enumerate(products_ws_titles):
        spec_on_shelf.write(0, i, title, bold)
        spec_off_shelf.write(0, i, title, bold)
    row_on = 1
    row_off = 1
    for spec in specs:
        is_on_shell = spec.is_on_shell and spec.product.is_on_shell
        ws = spec_on_shelf if is_on_shell else spec_off_shelf
        row = row_on if is_on_shell else row_off
        ws.write(row, 0, spec.product.category.name)  # 类型
        ws.write(row, 1, spec.product.name)  # 商品名称
        ws.write(row, 2, spec.name)  # 规格名称
        ws.write(row, 3, spec.price / 100.0)  # 单价
        ws.write(row, 4, spec.unit)  # 单位
        ws.write(row, 5, spec.description)  # 描述
        ws.write(row, 6, spec.deposit)  # 押金
        ws.write(row, 7, spec.deposit_desc)  # 押金描述
        if spec.discount:
            ws.write(row, 8, spec.discount / 100.0)  # 优惠价
        if is_on_shell:
            row_on += 1
        else:
            row_off += 1
